using RabbitMQ.Client;
namespace Beauty.Net.RabbitMQ.PublishSubscribe
{
    /// <summary>
    /// 发布/订阅模式消费者
    /// </summary>
    public class PublishSubscribeConsumer<T> : RabbitMQConsumerBase<T>
    {
        private readonly bool _useTemporaryQueue;
        private readonly string _generatedQueueName;

        public PublishSubscribeConsumer(IRabbitMQConnectionManager connectionManager,
                                      string exchangeName,
                                      MessageHandler<T> messageHandler,
                                      string? queueName = null,
                                      bool autoAck = false)
            : base(connectionManager, exchangeName, queueName ?? string.Empty, string.Empty, messageHandler, autoAck)
        {
            _useTemporaryQueue = string.IsNullOrEmpty(queueName);
            _generatedQueueName = string.Empty;
        }

        protected override void SetupExchangeAndQueue()
        {
            if (_channel == null) throw new InvalidOperationException("Channel not initialized");
            
            // 声明扇型交换机
            _channel.ExchangeDeclare(exchange: ExchangeName,
                                   type: ExchangeType.Fanout,
                                   durable: true,
                                   autoDelete: false,
                                   arguments: null);

            // 如果使用临时队列
            if (_useTemporaryQueue)
            {
                // 创建一个非持久化、排他的、自动删除的队列
                QueueName = _channel.QueueDeclare().QueueName;
            }
            else
            {
                // 声明持久化队列
                _channel.QueueDeclare(queue: QueueName,
                                    durable: true,
                                    exclusive: false,
                                    autoDelete: false,
                                    arguments: null);
            }

            // 将队列绑定到交换机
            _channel.QueueBind(queue: QueueName,
                              exchange: ExchangeName,
                              routingKey: string.Empty);
        }
    }
}